import axios from 'axios'
import { Notification, MessageBox, Message } from 'element-ui'
import { getToken } from '@/utils/auth'
import errorCode from '@/utils/errorCode'
// 引入本地存储
import {setJsonObjectToLocal,getJsonObjectFromLocal,clearDataFromLocal} from '@/utils/localstorage'
// 引入常量
import CONSTANT from '@/utils/constant'

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分  172.16.2.232
  // baseURL: process.env.VUE_APP_BASE_PATH,
  baseURL: '/prod-api',
  // baseURL: 'https://villagetest.baiyiyl.com/baiyi',
  // baseURL: 'https://village.baiyiyl.com/baiyi',
  // 超时
  timeout: 100000
})
// 拦截url地址 处理统一设置
function interceptorUrl(config){
  // 是否需要设置 token
  const isToken = (config.headers || {}).isToken === false
  console.log('-------------------request拦截器 isToken='+isToken,'isToken');
  console.log(getToken(),'getToken()');
  console.log("临时登录token",sessionStorage.getItem("loginToken"));
  if (getToken() && !isToken) {
    config.headers['token'] = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
  }else if(sessionStorage.getItem("loginToken")){
    config.headers['token'] =sessionStorage.getItem("loginToken")
  }
  // get请求映射params参数
  if (config.method === 'get' && config.params) {
    let url = config.url + '?';
    for (const propName of Object.keys(config.params)) {
      const value = config.params[propName];
      var part = encodeURIComponent(propName) + "=";
      if (value !== null && typeof(value) !== "undefined") {
        if (typeof value === 'object') {
          for (const key of Object.keys(value)) {
            let params = propName + '[' + key + ']';
            var subPart = encodeURIComponent(params) + "=";
            url += subPart + encodeURIComponent(value[key]) + "&";
          }
        } else {
          url += part + encodeURIComponent(value) + "&";
        }
      }
    }
    url = url.slice(0, -1);
    config.params = {};
    config.url = url;
  }
  console.log("request请求参数---->",config);
  return config
}

// request拦截器 拦截url
service.interceptors.request.use(config => {
  console.log("===========================拦截第2次==========================")
  return interceptorUrl(config)
}, error => {
    console.log(error)
    Promise.reject(error)
})
// 拦截是否刷新token
async function interceptorRefreshToken(config){
  // 验证token过期
  let localToken = getJsonObjectFromLocal(sessionStorage,CONSTANT.REFRESH_TOKEN);
  if(localToken){
    // 查看是否需要验签
    let time = new Date().getTime();
    console.log("是否需要刷新token------------->")
    console.log("相差毫秒数----->",localToken.expireTtl-time)
    console.log("相差天数----->",(localToken.expireTtl-time)/1000/60/60/24)
    if(localToken.expireTtl-time< CONSTANT.REFRESH_TIME){
      // 需要刷新
      await axios.get(process.env.VUE_APP_BASE_PATH+"/api/auth/refresh_token?refreshToken="+localToken.refreshToken+"&token="+localToken.token)
        .then(function (ret) {
          //不是实际的数据
          console.log("需要刷新，刷新token-------------------->",ret)
          console.log("这个才是真正的数据  data是固定的---->",ret.data);//这个才是真正的数据  data是固定的
          if(ret.data.code==0){
            localToken.expireTtl = ret.data.data.expireTTl;
            localToken.refreshToken = ret.data.data.refreshToken;
            setJsonObjectToLocal(window.sessionStorage,CONSTANT.REFRESH_TOKEN,localToken)
          }
        });
    }
  }
  return config;
}
// request拦截器  拦截token是否需要续签
service.interceptors.request.use(config => {
  console.log("===========================拦截第1次==========================")
  return interceptorRefreshToken(config)
}, error => {
  console.log(error)
  Promise.reject(error)
})

service.interceptors.response.use(res => {
    console.log("-------------response响应拦截器------------");
    console.log(res);
    // 未设置状态码则默认成功状态
    const code = res.data.code || 200;
    console.log(code,"res.data.code");
    // 获取错误信息
    const msg = errorCode[code] || res.data.msg || errorCode['default']
    if (code === 260005) {
      MessageBox.confirm('登录状态已过期，您可以继续留在该页面，或者重新登录', '系统提示', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        /*store.dispatch('LogOut').then(() => {
          location.href = '/index';
        })*/
        sessionStorage.clear();
        localStorage.clear();
        location.href = '/login';
      })
    } else if (code === 500) {
      Message({
        message: msg,
        type: 'error'
      })
      return Promise.reject(new Error(msg))
    }else if (code !== 200) {
      Notification.error({
        title: msg
      })
      return Promise.reject('error')
    } else if (code == 280002){
      return res.data
    }else{
      return res.data
    }
  },
  error => {
    console.log('err' + error)
    let { message } = error;
    if (message == "Network Error") {
      message = "后端接口连接异常";
    }
    else if (message.includes("timeout")) {
      message = "系统接口请求超时";
    }
    else if (message.includes("Request failed with status code")) {
      message = "系统接口" + message.substr(message.length - 3) + "异常";
    }
    Message({
      message: message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
